﻿/*
 * Copyright © 2011 Tristan Reeves, treeves@gmail.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
using System;
using System.Linq.Expressions;
using System.Reflection;

namespace Sprinkles.ExpressionHandlers
{
    internal class PropertyExpressionHandler<T>
    {
        private bool ProcessInternal(MemberExpression expression)
        {
            if (expression == null) return false;
            if (expression.NodeType != ExpressionType.MemberAccess) return false;
            PropertyInfo = expression.Member as PropertyInfo; 
            if (PropertyInfo == null) return false;

            if (PropertyInfo.IsSpecialName) return false;
            var target = expression.Expression as ParameterExpression;
            if (target == null) return false;
            if (target.Type != typeof(T)) return false;
            if (PropertyInfo.GetIndexParameters().Length > 0) return false;
            if (!PropertyInfo.CanWrite) return false;

            return true;
        }
        public void Process(LambdaExpression expression, Type returnType)
        {
            IsValid = false;

            var me = expression.Body as MemberExpression;
            if (me == null) return;
            IsValid = ProcessInternal(me);
        }

        public PropertyInfo PropertyInfo { get; private set; }
        public bool IsValid { get; private set; } 
    }
}
